package stage;

import fileoperation.FileCreation;
import gitobject.Blob;
import repository.Repository;

import java.io.*;
import java.util.*;

public class StagingArea {

    private HashMap<String, String> index = new HashMap<>();

    private static String path = Repository.getGitDir();

    public StagingArea() throws IOException {
        if(!new File(path + File.separator + "index").exists()) {
            FileCreation.createFile(path, "index", "");
        }else {
            index = getHashmap();
        }
    }

    public HashMap<String, String> getHashmap() throws IOException {
        File index = new File(path + File.separator + "index");
        FileInputStream fis = new FileInputStream(index);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        HashMap<String, String> list = new HashMap<>();
        try{
            String line = br.readLine();

            while(line != null){
                String[] s = line.split(" ");
                list.put(s[0], s[1]);
                line = br.readLine();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        br.close();
        fis.close();

        return list;
    }

    public boolean inIndex(File file){
        String filePath = file.getPath();
        if(index.containsValue(filePath))   return true;
        else    return false;
    }


    public void insertIndex (File file) throws Exception{
        Blob blob = new Blob(file);
        String workDir = Repository.getWorkTree();
        String fileName = file.getPath().substring(workDir.length() + 1);
        String key = blob.getKey();
        index.put(key, fileName);
    }

    public void writeIndex() throws IOException{
        File file = new File(path + File.separator + "index");
        FileWriter fileWriter = new FileWriter(file);
        for(Map.Entry<String, String> entry : index.entrySet()){
            fileWriter.write(entry.getKey() + " " + entry.getValue() + "\n");
        }
        fileWriter.flush();
        fileWriter.close();
    }

    public void removeKeyValue (File file) throws Exception{
        Blob blob = new Blob(file);
        String s = blob.getKey();
        index.remove(s);
    }

    public String indexToString() {
        StringBuilder stringBuilder = new StringBuilder();
        for(Map.Entry<String, String> entry : index.entrySet()){
            stringBuilder.append(entry.getKey()).append(" ").append(entry.getValue()).append("\n");
        }
        String s = stringBuilder.toString();
        return s;
    }

    public void clearIndex() throws Exception{
        index.clear();
        writeIndex();
    }

}
